﻿using System;
using DotNetEx;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Mrc.AuthService;
using Mrc.Entities;
namespace Mrc.AuthCenter
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class LoginAttribute : Attribute, IAuthorizationFilter
    {
        public LoginAttribute()
        {

        }
        public virtual void OnAuthorization(AuthorizationFilterContext filterContext)
        {
            if (filterContext.Result != null)
                return;
            var token = "";
            filterContext.HttpContext.Request.Cookies.TryGetValue("MRCTOKEN", out token);
            if (token.IsNullOrEmpty())
            {
                Valid(filterContext);
                return;
            }
            var validateResult = TokenManager.Validate(token, payLoad =>
             {
                 var success = true;
                 success = success && payLoad["aud"]?.ToString() == "user";
                 if (success)
                 {

                 }
                 return success;
             });
            if (validateResult)
            {
                return;
            }
            Valid(filterContext);
            return;
        }

        private void Valid(AuthorizationFilterContext filterContext)
        {
            HttpRequest httpRequest = filterContext.HttpContext.Request;
            if (httpRequest.IsAjaxRequest())
            {
                AjaxResult result = AjaxResult.CreateResult(ResultStatus.NotLogin, "未登录或登录超时，请重新登录");
                string json = JsonHelper.Serialize(result);
                ContentResult contentResult = new ContentResult() { Content = json };
                filterContext.Result = contentResult;
                return;
            }
            else
            {
                string url = filterContext.HttpContext.Content("/home/PageNoAuth");
                url = string.Concat(url, "?returnUrl=", httpRequest.Path);
                RedirectResult redirectResult = new RedirectResult(url);
                filterContext.Result = redirectResult;
                return;
            }
        }
    }
}
